package org.wii.base.exception;

import org.wii.base.annotation.ExceptionModule;
import org.wii.base.config.IWiiAppConfig;
import org.wii.base.exception.constant.ExceptionModuleConstant;
import org.wii.base.exception.constant.ExceptionTypeEnum;
import org.wii.base.exception.constant.IExceptionErrCode;
import org.wii.base.utils.SpringBeanUtil;

/**
 * 基础异常类
 * @author tanghong on 2022/12/22
 */
public class IWiiException extends RuntimeException{
    /**错误码*/
    protected long code;
    /**描述*/
    protected String message;

    protected IExceptionErrCode exceptionErrCode;

    public IWiiException(long code, String message){
        super("[[异常码:" + code + "===描述:" + message +"]]");
        this.code = code;
        this.message = message;
    }

    public IWiiException(IExceptionErrCode exceptionErrCode){
        super("[[异常码:" + exceptionErrCode.getCode() + "===描述:" + exceptionErrCode.getMessage() +"]]");
        this.code = exceptionErrCode.getCode();
        this.message = exceptionErrCode.getMessage();
        this.exceptionErrCode = exceptionErrCode;
    }

    public IWiiException(IExceptionErrCode exceptionErrCode, Object... args){
        super(String.format(exceptionErrCode.getMessage(), args));
        this.code = exceptionErrCode.getCode();
        this.message = exceptionErrCode.getMessage();
        this.exceptionErrCode = exceptionErrCode;
    }

    public long getCode() {
        // 错误类型+系统编码+模块编码+常规错误码
        if (null != exceptionErrCode){
            Class<?> errClass = exceptionErrCode.getClass();
            StringBuilder sbf = new StringBuilder();
            ExceptionModule exceptionModule = errClass.getAnnotation(ExceptionModule.class);
            IWiiAppConfig appConfig = SpringBeanUtil.getBean(IWiiAppConfig.class);
            if (null != exceptionModule){
                sbf.append(exceptionModule.type().getCode())
                .append(appConfig.getCode())
                .append(exceptionModule.code())
                .append(this.code);
            } else {
                sbf.append(ExceptionTypeEnum.UNKNOWN.getCode())
                .append(appConfig.getCode())
                .append(ExceptionModuleConstant.UNKNOWN)
                .append(this.code);
            }
            return Long.parseLong(sbf.toString());
        }
        return code;
    }

}
